import os
from apps.commonapp.models import Company,School
from django.views.generic import View
from .models import User,Uservalid
from django.conf import settings
from apps.resp.response import USER_EXIT_ERROR,PASSWD_ERROR,NOT_UPLOAD_FILE_ERROR,HAS_BENN_DO_ERROR,Response,USER_NOT_EXIT_ERROR,PARAMS_ERROR
from apps.utils.auth import jwt_required,create_jwt

class UserView(View):
    def get(self,req):
        pass
    # 创建用户
    def post(self,req):
        username = req.POST.get("username")
        password = req.POST.get("password")
        users = User.objects.filter(username=username)
        if len(users) != 0:
            raise USER_EXIT_ERROR
        User.objects.create(username=username,password=User.pwd(password))
        return Response.SUCCESS()
    
class AuthView(View):
    def post(self,req):
        username = req.POST.get("username")
        password = req.POST.get("password")
        users = User.objects.filter(username=username)
        if len(users) == 0:
            raise USER_NOT_EXIT_ERROR
        user = users[0]
        is_verify = User.verify(username=username,passwd=password)
        if is_verify:
            token = create_jwt(user.id)
            return Response.SUCCESS(data={"token":token})
        else:
            raise PASSWD_ERROR


class UservalidView(View):
 @jwt_required
 def post(self, req):
    user_id = req.POST.get("user")
    company_id = req.POST.get("company")
    school_id = req.POST.get("school")
    c_id_card = req.POST.get("c_id_card")
    s_id_card = req.POST.get("s_id_card")
    u_id_card = req.POST.get("u_id_card")
    boss_phone = req.POST.get("boss_phone")
    user = None
    company = None
    school = None
    # 检查用户是否存在并获取
    userset = User.objects.filter(id=user_id)
    if not userset.exists():
        raise USER_NOT_EXIT_ERROR
    else:
        user = userset.first()
    # 检查用户是否已经验证
    if Uservalid.objects.filter(user=user).exists():
        raise HAS_BENN_DO_ERROR

    # 尝试获取公司和学校，若不存在则赋值为 None
    if not (company_id or school_id):
        raise PARAMS_ERROR

    company = Company.objects.filter(id=company_id).first() if company_id else None
    school = School.objects.filter(id=school_id).first() if school_id else None

    # 检查用户的有效性
    if user.is_valid:
        return Response.SUCCESS()

    # 创建新的用户验证记录
    Uservalid.objects.create(user=user, company=company, school=school, is_active=False,company_id_card=c_id_card,school_id_card=s_id_card,user_id_card=u_id_card,boss_phone=boss_phone)
    return Response.SUCCESS()

class FileUpLoad(View):
    def post(self,req):
        if 'file' not in req.FILES:
            raise NOT_UPLOAD_FILE_ERROR
        import uuid

        file = req.FILES['file']
        fname = "{}_{}".format(uuid.uuid4().hex,file.name)
        # 定义文件保存路径
        save_path = os.path.join(settings.MEDIA_ROOT, fname)
        os.makedirs(settings.MEDIA_ROOT, exist_ok=True)
        
        # 保存文件到媒体目录
        with open(save_path, 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)
        
        # 构建文件的访问URL
        file_url = os.path.join(settings.MEDIA_URL, fname)
        return Response.SUCCESS(data={
            "file_url":file_url
        })
    
